﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using VAdvantage.Logging;
using System.Text;
using VAdvantage.Classes;
using VAdvantage.Grids;
using VAdvantage.Model;
using VAdvantage.Utility;
using System.Data;
using VAdvantage.DataBase;

namespace VAdvantage.Dialogs
{
    public partial class RecordInfo : ChildWindow
    {


       // SLControls.Controls.VLabel lblInfo = new SLControls.Controls.VLabel();
        /** The Data		*/
        private List<List<String>> m_data = new List<List<String>>();
        /**	Logger			*/
        protected VLogger log = VLogger.GetVLogger(typeof(RecordInfo).FullName);
        /** The Data		*/
        //private Vector<Vector<String>> m_data = new Vector<Vector<String>>();
        /** Info			*/
        private StringBuilder _info = new StringBuilder();


        /** Date Time Format		*/
        private SimpleDateFormat _dateTimeFormat = DisplayType.GetDateFormat
            (DisplayType.DateTime);
        /** Date Format			*/
        private SimpleDateFormat _dateFormat = DisplayType.GetDateFormat
            (DisplayType.DateTime);
        /** Number Format		*/
        private Format _numberFormat = DisplayType.GetNumberFormat(DisplayType.Number);
        /** Amount Format		*/
        private Format _amtFormat = DisplayType.GetNumberFormat(DisplayType.Amount);
        /** Number Format		*/
        private Format _intFormat = DisplayType.GetNumberFormat(DisplayType.Integer);



        public RecordInfo()
        {
           
        }

       
        public RecordInfo(String title, DataStatusEvent dse)
            : this()
        {
           // this.SetTitle(title);
            
            InitializeComponent();
            this.Title = title;
            LayoutRoot.Background = new SolidColorBrush(DataBase.GlobalVariable.WINDOW_BACK_COLOR);
            try
            {
                bool output = false;
                //JbInit(DynInit(dse, title));
                System.Threading.ThreadPool.QueueUserWorkItem(delegate
                {
                    output = DynInit(dse, title);
                    Dispatcher.BeginInvoke(() => JbInit(output));

                });

                
                

            }
            catch (Exception e)
            {
                log.Log(Level.SEVERE, "", e);
            }
        }	//	RecordInfo


        private void btnOk_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }
        /**
	 * 	Static Layout
	 *	@throws Exception
	 */
        private void JbInit(bool showTable)
        {
            lblInfo.Content = _info.ToString();
            lblInfo.Foreground = new SolidColorBrush (Colors.Blue);
            //
            if (showTable)
            {
                //CommonFunctions.SetDataGridPrperties(dgrvData);
               
                dgrvData.IsReadOnly = true;
                //mainPanel.add (info, BorderLayout.NORTH);
                //mainPanel.add (scrollPane, BorderLayout.CENTER);
                //scrollPane.getViewport().add(table);
                //this.Size = new System.Drawing.Size(450, 250);
                //scrollPane.setPreferredSize(new Dimension(500,100));
            }
            //else
            //{
            //    //info.setPreferredSize(new Dimension(400,75));
            //    //mainPanel.add (info, BorderLayout.CENTER);
            //}
        }








        /**
         * 	Dynamic Init
         *	@param dse data status event
         *	@param title title
         *	@return true if table initialized
         */
        private bool DynInit(DataStatusEvent dse, String title)
        {
            if (dse.CreatedBy == null || dse.CreatedBy == -1)
                return false;
            //  Info
            MUser user = MUser.Get(Envs.GetContext(), dse.CreatedBy);
            _info.Append(" ")
                .Append(Msg.Translate(Envs.GetContext(), "CreatedBy"))
                .Append(": ").Append(user.GetName())
                .Append(" - ").Append(String.Format("{0:D}", dse.Created)).Append("\n");

            if (!dse.Created.Equals(dse.Updated)
                || !dse.CreatedBy.Equals(dse.UpdatedBy))
            {
                if (!dse.CreatedBy.Equals(dse.UpdatedBy))
                    user = MUser.Get(Envs.GetContext(), dse.UpdatedBy);
                _info.Append(" ")
                    .Append(Msg.Translate(Envs.GetContext(), "UpdatedBy"))
                    .Append(": ").Append(user.GetName())
                    .Append(" - ").Append(_dateTimeFormat.Format(dse.Updated)).Append("\n");
            }
            if (dse.Info != null && dse.Info.Length > 0)
                _info.Append("\n (").Append(dse.Info).Append(")");

            //	Title
            if (dse.AD_Table_ID != 0)
            {
                MTable table1 = MTable.Get(Envs.GetContext(), dse.AD_Table_ID);
               // SetTitle(title + " - " + table1.GetName());
            }

            //	Only Client Preference can view Change Log
            if (!MRole.PREFERENCETYPE_Client.Equals(MRole.GetDefault().GetPreferenceType()))
                return false;

            int Record_ID = 0;
            if (dse.Record_ID is int)
                Record_ID = (int)dse.Record_ID;
            else
                log.Info("dynInit - Invalid Record_ID=" + dse.Record_ID);
            if (Record_ID == 0)
                return false;

            //Data
            String sql = "SELECT AD_Column_ID, Updated, UpdatedBy, OldValue, NewValue "
                + " FROM AD_ChangeLog "
                + " WHERE AD_Table_ID=" + dse.AD_Table_ID + " AND Record_ID=" + Record_ID
                + " ORDER BY Updated DESC";
            try
            {
                DataSet ds = DB.ExecuteDataset(sql,null,null);

                foreach (DataRow dr in ds.Tables[0].Rows)
                {

                    AddLine(Util.GetValueOfInt(dr[0]), Util.GetValueOfDateTime(dr[1]), Util.GetValueOfInt(dr[2]),
                             dr[3].ToString(), dr[4].ToString());
                }
                //    rs.close ();
                //    pstmt.close ();
                //    pstmt = null;
            }
            catch (Exception e)
            {
                log.Log(Level.SEVERE, sql, e);
            }

            List<String> columnNames = new List<String>();
            columnNames.Add(Msg.Translate(Envs.GetCtx(), "AD_Column_ID"));
            columnNames.Add(Msg.Translate(Envs.GetCtx(), "NewValue"));
            columnNames.Add(Msg.Translate(Envs.GetCtx(), "OldValue"));
            columnNames.Add(Msg.Translate(Envs.GetCtx(), "UpdatedBy"));
            columnNames.Add(Msg.Translate(Envs.GetCtx(), "Updated"));
            //DefaultTableModel model = new DefaultTableModel(m_data, columnNames);

            Dispatcher.BeginInvoke (()=> BindGrid(columnNames, m_data));
            //table.setModel(model);
            //table.autoSize(false);
            //return false;
            return true;
        }


        private void BindGrid(List<string> columnNames, List<List<string>> m_data)
        {

            DataTable dt = new DataTable();

            if (m_data.Count == 0)
            {
                //dgrvData.Visibility = Visibility.Collapsed;
                return;

            }
            else
            {
                //scroll.Visibility = Visibility.Visible;
                dgrvData.Visibility = Visibility.Visible;
            }

            for (int col = 0; col < columnNames.Count; col++)
            {
                DataColumn column =new DataColumn (columnNames[col], typeof(string));
              
                dt.Columns.Add(column);
                DataGridTextColumn txtcol = new DataGridTextColumn();
                txtcol.Binding = new System.Windows.Data.Binding(dt.Columns[col].ColumnName);
                txtcol.Header = (dt.Columns[col].ColumnName);
                
                dgrvData.Columns.Add(txtcol);
            }
            
           
            for (int i = 0; i < m_data.Count; i++)
            {
                DataRow datarow=new DataRow(dt);
            
                for (int col=0;col<dt.Columns.Count;col++)
                {
                    datarow[col]=m_data[i][col];
                }
                dt.Rows.Add(datarow);
            }
           
            dgrvData.ItemsSource = dt.GetBindableData(new Connector());

        }

        private void DisposeLocal()
        {
            log = null;
            _info = null;
            _dateTimeFormat = null;
            _dateFormat = null;
            _numberFormat = null;
            _amtFormat = null;
            _intFormat = null;
        }


        private void AddLine(int AD_Column_ID, DateTime? Updated, int UpdatedBy,
          String OldValue, String NewValue)
        {
            List<String> line = new List<String>();
            //	Column
            MColumn column = MColumn.Get(Envs.GetCtx(), AD_Column_ID);
            line.Add(column.GetName());
            //
            if (OldValue != null && OldValue.Equals(MChangeLog.NULL))
                OldValue = null;
            String showOldValue = OldValue;
            if (NewValue != null && NewValue.Equals(MChangeLog.NULL))
                NewValue = null;
            String showNewValue = NewValue;
            //
            try
            {
                if (DisplayType.IsText(column.GetAD_Reference_ID()))
                {
                    ;
                }
                else if (column.GetAD_Reference_ID() == DisplayType.YesNo)
                {
                    if (OldValue != null)
                    {
                        bool yes = OldValue.Equals("true") || OldValue.Equals("Y");
                        showOldValue = Msg.GetMsg(Envs.GetCtx(), yes ? "Y" : "N");
                    }
                    if (NewValue != null)
                    {
                        bool yes = NewValue.Equals("true") || NewValue.Equals("Y");
                        showNewValue = Msg.GetMsg(Envs.GetCtx(), yes ? "Y" : "N");
                    }
                }
                else if (column.GetAD_Reference_ID() == DisplayType.Amount)
                {
                    if (OldValue != null)
                        showOldValue = String.Format(_amtFormat.GetFormat(), OldValue);//.fo
                    //.format (new BigDecimal (OldValue));
                    if (NewValue != null)
                        showNewValue = String.Format(_amtFormat.GetFormat(), NewValue);//.ToString(_amtFormat.GetFormat());//  m_amtFormat
                    //.format (new BigDecimal (NewValue));
                }
                else if (column.GetAD_Reference_ID() == DisplayType.Integer)
                {
                    if (OldValue != null)
                        showOldValue = String.Format(_intFormat.GetFormat(), OldValue);//.ToString(_intFormat.GetFormat());// m_intFormat.format (new Integer (OldValue));
                    if (NewValue != null)
                        showNewValue = String.Format(_intFormat.GetFormat(), NewValue);//.ToString(_intFormat.GetFormat());//m_intFormat.format (new Integer (NewValue));
                }
                else if (DisplayType.IsNumeric(column.GetAD_Reference_ID()))
                {
                    if (OldValue != null)
                        showOldValue = String.Format(_numberFormat.GetFormat(), OldValue);//.ToString(_numberFormat.GetFormat());//m_numberFormat.format (new BigDecimal (OldValue));
                    if (NewValue != null)
                        showNewValue = String.Format(_numberFormat.GetFormat(), NewValue);//.ToString(_numberFormat.GetFormat()); //m_numberFormat.format (new BigDecimal (NewValue));
                }
                else if (column.GetAD_Reference_ID() == DisplayType.Date)
                {
                    if (OldValue != null)
                        showOldValue = _dateFormat.Format(OldValue);// m_dateFormat.format (Timestamp.valueOf (OldValue));
                    if (NewValue != null)
                        showNewValue = _dateFormat.Format(NewValue);// m_dateFormat.format (Timestamp.valueOf (NewValue));
                }
                else if (column.GetAD_Reference_ID() == DisplayType.DateTime)
                {
                    if (OldValue != null)
                        showOldValue = _dateTimeFormat.Format(OldValue);// (Timestamp.valueOf (OldValue));
                    if (NewValue != null)
                        showNewValue = _dateTimeFormat.Format(NewValue);// (Timestamp.valueOf (NewValue));
                }
                else if (DisplayType.IsLookup(column.GetAD_Reference_ID()))
                {
                    MLookup lookup = MLookupFactory.Get(Envs.GetCtx(), 0,
                        AD_Column_ID, column.GetAD_Reference_ID(),
                         column.GetColumnName(),
                        column.GetAD_Reference_Value_ID(),
                        column.IsParent(), null);
                  
                    if (OldValue != null)
                    {
                        Object key = OldValue;
                        if (column.GetAD_Reference_ID() != DisplayType.List
                            && column.GetColumnName().EndsWith("_ID"))
                        {
                            try
                            {
                                key = Convert.ToInt32(OldValue);
                            }
                            catch (Exception e)
                            {
                            }
                        }
                        NamePair pp = lookup.Get(key);
                        if (pp != null)
                            showOldValue = pp.GetName();
                    }
                    if (NewValue != null)
                    {
                        Object key = NewValue;
                        if (column.GetAD_Reference_ID() != DisplayType.List
                            && column.GetColumnName().EndsWith("_ID"))
                        {
                            try
                            {
                                key = Convert.ToInt32(NewValue);
                            }
                            catch (Exception e)
                            {
                            }
                        }
                        NamePair pp = lookup.Get(key);
                        if (pp != null)
                            showNewValue = pp.GetName();
                    }
                }
                else if (DisplayType.IsLOB(column.GetAD_Reference_ID()))
                {
                }

            }
            catch (Exception e)
            {
                log.Log(Level.WARNING, OldValue + "->" + NewValue, e);
            }
            //
            line.Add(showNewValue);
            line.Add(showOldValue);
            //	UpdatedBy
            MUser user = MUser.Get(Envs.GetCtx(), UpdatedBy);
            line.Add(user.GetName());
            //	Updated
            line.Add(_dateFormat.Format(Updated));
            m_data.Add(line);
        }

      

     


      
    }
}

